# coding=utf8
import commands
import ConfigParser


def check_system_disk():
    """
    检查系统硬盘空间
    :return:
    """
    print(u"系统当前硬盘空间")
    disk = commands.getoutput("df -h")
    print(disk)
    print("\n")


def check_system_memory():
    """
    检查系统内存
    :return:
    """
    print(u"系统当前内存 MB")
    memory = commands.getoutput("free -m")
    print(memory)
    print("\n")


def check_port_connections(port):
    """
    检查端口的连接数
    :param port:
    :return:
    """
    port_current_connect = commands.getoutput('netstat -nat|grep -i "{0}"|wc -l'.format(port))
    print(u"端口{0}当前连接数{1}".format(port, port_current_connect))
    print("\n")


def check_system_top_10_program():
    """
    检查系统消耗前10的程序
    :return:
    """
    top_10_cup = commands.getoutput("ps auxw|head -1;ps auxw|sort -rn -k3|head -10")
    top_10_memory = commands.getoutput("ps auxw|head -1;ps auxw|sort -rn -k4|head -10")
    print(u"cup消耗前10程序\n")
    print(top_10_cup)
    print("\n")
    print(u"内存消耗前10程序\n")
    print(top_10_memory)
    print("\n")


def check_system_last_10_cmd():
    """
    检查系统最后的10条指令
    :return:
    """
    last_10_cmd = commands.getoutput("dmesg | tail")
    print(u"系统最后的10条指令\n")
    print(last_10_cmd)
    print("\n")


def load_conf():
    """
    加载配置
    :return: 返回配置
    """
    conf = ConfigParser.ConfigParser()
    conf.read('devops.cfg')
    port = int(conf.get("connection_count", "port"))
    if not port:
        port = 80
    cfg = {
        'connect_port': port
    }

    return cfg


def main():
    config = load_conf()
    check_system_disk()
    check_system_memory()
    check_system_top_10_program()
    check_system_last_10_cmd()
    check_port_connections(config.get('connect_port'))


if __name__ == '__main__':
    main()
